﻿using Gfw.Infrastructure.Account;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Models.Account;
using Gfw.Repositories.Account;
using Gfw.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gfw.Infrastructure.Facilities
{
    /// <summary>
    /// 系统支出
    /// </summary>
    public class SystemOutlayFacility : IFacility
    {
        #region Private Fields

        protected decimal _count;
        protected int _type;
        protected string _handlerID, _remark;

        #endregion

        #region 构造函数与初始化

        public SystemOutlayFacility(decimal count, int type, string handlerID, string remark)
        {
            this._count = count;
            this._type = type;
            this._handlerID = handlerID;
            this._remark = remark;
        }

        #endregion

        #region IFacility 成员

        /// <summary>
        /// 系统扣费操作（老板权限）
        /// </summary>
        /// <param name="unitOfWork"></param>
        public virtual void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            try
            {
                if (unitOfWork != null)
                    throw new GfwException("当前事务只能作为原子事务，不允许与其它操作公用数据库事务。");

                UnitOfWork work = unitOfWork ?? new UnitOfWork();
                ActCompanyBargainRepository bargainRep = new ActCompanyBargainRepository(); // 修改：公司帐户交易明细
                ActCompanyPayRepository payRep = new ActCompanyPayRepository(); // 修改：公司扣费记录表

                DateTime payDate = DateTime.Now;
                ActCompanyPay comPay = new ActCompanyPay()
                {
                    Id = Guid.NewGuid().ToString(),
                    Handlerid = this._handlerID,
                    PayMoney = this._count,
                    PayType = this._type,
                    PayDate = payDate,
                    PayAbstract = this._remark,
                };

                ActCompanyBargain comBargain = new ActCompanyBargain()
                {
                    Id = Guid.NewGuid().ToString(),
                    Userid = this._handlerID,
                    TradeType = this._type,
                    Income = 0,
                    Outlay = this._count,
                    Balance = 0,
                    TradeDate = payDate,
                    TradeAbstract = "【系统支出】" + this._remark,
                    AwardSerialNo = "",
                    TaxationSerialNo = "",
                };

                payRep.Save(comPay, work);
                bargainRep.Save(comBargain, work);

                if (unitOfWork == null)
                    work.Commit();
            }
            catch (System.Exception ex)
            {
                throw new GfwVerifyException(ex.Message);
            }
        }

        #endregion
    }
}
